package com.momo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.momo.configuration.open.EmojiFilter;
import com.momo.utils.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Kagome on 2019/5/21.
 */
@RestController
@RequestMapping(value = "user")
public class LoginController {
    protected static final Logger LOG = LoggerFactory.getLogger(LoginController.class);

    // 公众号APPID
    public static final String WX_APPID = "XXXXXXXXXXXX";
    // 公众号SECRET
    public static final String WX_APP_SECRET = "XXXXXXXXXXXX";

    @RequestMapping(value = "login", method = RequestMethod.GET)
    public void toLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获取cookie中的openid
        String openid = request.getHeader("openid");
        String unionid = request.getHeader( "unionid");
        // 定义微信授权之后的跳转地址命名方式为(http://你的网址+/user/login?u=)
        String reUrl = "";
        // 获取需要跳转的url
        String u = request.getParameter("u");
        LOG.error("需要跳转的url为:", u);
        // 判断如果openid不存在，则获取code
        // 如果拦截到的跳转的地址为空则给个默认值
        if (StringUtils.isBlank(u)) {
            u = "/indexController/index";
        }
        if (StringUtils.isBlank(openid) || StringUtils.isBlank(unionid)) {
            // 获取code
            String code = request.getParameter("code");
            LOG.error("code:", code);
            if (StringUtils.isBlank(code)) {
                // 跳转到微信端获取code
                String redrictUrl = response.encodeURL(reUrl + response.encodeURL(u));
                String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WX_APPID + "&redirect_uri="
                        + redrictUrl + "&response_type=code&scope=snsapi_userinfo&state=0#wechat_redirect";
                try {
                    response.sendRedirect(url);
                } catch (IOException e) {
                    // logger.error("url:重定向错误");
                }
                return;
            } else {
                // 获取用户信息
                JSONObject object = getSnsapiUserinfo(request, code);
                if (object != null) {
                    String user_unionid = object.getString("unionid");
                    String user_openid = object.getString("openid");
                    if (StringUtils.isBlank(user_unionid) || StringUtils.isBlank(user_openid)) {
                        return;
                    }
                    String headimgurl = object.getString("headimgurl");
                    String nickname = EmojiFilter.filterEmoji(object.getString("nickname"));
                }

            }
        }
        // 返回客户访问页面
        try {
            response.sendRedirect(u);
        } catch (IOException e) {
            // logger.error("url:重定向错误");
        }
    }

    public static JSONObject getSnsapiUserinfo(HttpServletRequest request, String code){
        JSONObject wxuser;

        String t_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WX_APPID + "&secret="
                + WX_APP_SECRET + "&code=" + code + "&grant_type=authorization_code";
       /* Proxy httproxy = new Proxy();
        final String result = httproxy.get(t_url, null);*/
        final String result =  HttpUtils.doGet(t_url);
        LOG.info("sns/oauth2/access_token：" + result);
        JSONObject obj = JSON.parseObject(result);
        String openid = obj.getString("openid");
        // 判断用户是否存在
        String t_access_token = obj.getString("access_token");
        String t_url_2 = "https://api.weixin.qq.com/sns/userinfo?access_token=" + t_access_token + "&openid=" + openid;
        final String res2 = HttpUtils.doGet(t_url_2);
        wxuser = JSON.parseObject(res2);
        LOG.info("网页授权获取用户基本信息：" + wxuser.toString());
        return wxuser;
    }
}
